package cn.bearspark.emoji.provider.service.impl;

import cn.bearspark.common.aop.autoparse.host.AutoParseHost;
import cn.bearspark.common.util.DataUtil;
import cn.bearspark.emoji.dto.AddEmojisDTO;
import cn.bearspark.emoji.provider.dao.buffer.EmojiBuffer;
import cn.bearspark.emoji.provider.service.bo.EmojiUrlBO;
import cn.bearspark.emoji.provider.dao.mapper.EmojiMapper;
import cn.bearspark.emoji.provider.dao.po.EmojiPO;
import cn.bearspark.emoji.provider.dao.po.ModuleEmojiPO;
import cn.bearspark.emoji.provider.service.EmojiService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author f
 */
@Service
@EnableScheduling
public class EmojiServiceImpl implements EmojiService, InitializingBean {

    private final EmojiMapper emojiMapper;

    private final EmojiBuffer emojiBuffer;

    public EmojiServiceImpl(EmojiMapper emojiMapper, EmojiBuffer emojiBuffer) {
        this.emojiMapper = emojiMapper;
        this.emojiBuffer = emojiBuffer;
    }

    @Override
    @AutoParseHost(EmojiUrlBO.class)
    public List<EmojiUrlBO> listAllEmojis() {
        return emojiBuffer.listAllEmojiUrl().stream().map(EmojiUrlBO::new).toList();
    }

    @Override
    @AutoParseHost(AddEmojisDTO.class)
    public void addEmojiList(AddEmojisDTO addEmojisDTO) {
        emojiMapper.insertEmojiList(addEmojisDTO.getModuleCode(), addEmojisDTO.getModuleDataId(),
                addEmojisDTO.getEmojiUrlList().stream().map(emojiBuffer::convertToEmojiId).toList());
    }

    @Override
    @AutoParseHost(EmojiUrlBO.class)
    public Map<Long, List<EmojiUrlBO>> mapEmojiSet(int moduleCode, Set<Long> moduleDataIdSet) {
        return DataUtil.group(
                moduleDataIdSet.size(),
                EmojiUrlBO.class,
                () -> emojiMapper.list(moduleCode, moduleDataIdSet),
                ModuleEmojiPO::getModuleDataId
        );
    }

    @Override
    public void delete(int moduleCode, long moduleDataId) {
        emojiMapper.delete(moduleCode, moduleDataId);
    }

    /**
     * 每天 0 点 0 分 0 秒，更新表情包缓存
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateEmojiCache() {
        emojiBuffer.caching(emojiMapper.listAllEmoji().stream().collect(Collectors.toMap(
                EmojiPO::getEmojiUrl, EmojiPO::getEmojiId
        )));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        emojiBuffer.caching(emojiMapper.listAllEmoji().stream().collect(Collectors.toMap(
                EmojiPO::getEmojiUrl, EmojiPO::getEmojiId
        )));
    }
}
